package com.example.demojimmer.common;

import com.example.demojimmer.application.dto.Results;
import com.example.demojimmer.domain.userauth.state.RespEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 只处理Controller抛出的异常
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Results handlerException(Exception e, HttpServletRequest request, HttpServletResponse response) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        log.error("请求uri【{}】", request.getRequestURI());
        log.error(e.getMessage(), e);
        Results results = new Results();
        results.setCode(RespEnum.ERROR.getCode());
        results.setMsg("Exception UNKNOWN_ERROR");
        results.setData(e.getMessage());
        return results;
    }


    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public Results handlerRuntimeException(RuntimeException e, HttpServletRequest request, HttpServletResponse response) {
        response.setStatus(HttpStatus.NOT_IMPLEMENTED.value());
        log.error("请求uri【{}】", request.getRequestURI());
        log.error(e.getMessage(), e);
        Results results = new Results();
        results.setCode(RespEnum.ERROR.getCode());
        results.setMsg("RuntimeException UNKNOWN_ERROR");
        results.setData(e.toString());
        return results;
    }


    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseBody
    public Results handleNoHandlerFoundException(NoHandlerFoundException e, HttpServletRequest request, HttpServletResponse response) {
        log.error("请求uri【{}】", request.getRequestURI());
        log.error(e.getMessage(), e);
        Results results = new Results();
        results.setCode(404);
        results.setMsg("找不到接口");
        results.setData(e.toString());
        return results;
    }

    @ExceptionHandler(ResponseStatusException.class)
    @ResponseBody
    public Results handleNoResourceFoundException(ResponseStatusException ex, HttpServletRequest request, HttpServletResponse response) {

        log.error("请求uri【{}】", request.getRequestURI());
        response.setStatus(HttpStatus.NOT_FOUND.value());
        // 可以设置不同的HTTP状态码，例如 HttpStatus.NOT_FOUND
        ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
        Results res = Results.res(HttpStatus.NOT_FOUND.value(), ex.getMessage(), null);
        return res;
    }

}